<template>
  <div class="h-full fixed top-0 left-0 bg-base-100 z-40 w-full overflow-y-scroll">
      <!--顶部栏-->
      <div class="z-50 flex justify-center items-center w-full h-16 text-md">
        <div class="w-2/12 md:w-1/12 flex justify-center">
          <div @click="router.push('/home')" class="">
            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5"
                 stroke="currentColor" class="w-6 h-6">
              <path stroke-linecap="round" stroke-linejoin="round" d="M19.5 12h-15m0 0l6.75 6.75M4.5 12l6.75-6.75"/>
            </svg>
          </div>
        </div>
        <div class="w-10/12 md:w-10/12 flex justify-start pl-2">
          {{ song?.name }}
        </div>
      </div>
      <div id="mainBox" @click="swap=!swap" class="flex justify-center items-center w-full h-[500px] border">
        <div :class="[{'hidden': swap!=true },'flex flex-col justify-center items-center w-full h-full']">
          <div class="relative w-72 h-72">
            <motion
                :initial="{
                 rotate:80
              }"
                id="playAnime"
                :class="['absolute right-[0%] -top-10 w-20 h-20 z-10 fill-secondary']"
                style="transform-origin:0 0"
            >
              <img src="../assets/vectors/cd_2.png"
                   class="object-cover filter transform-gpu absolute -left-[60%] -top-[61%] "
                   alt="未加载">
            </motion>
            <img src="../assets/vectors/cd.png"
                 class="object-cover absolute bottom-0 justify-center"
                 alt="未加载">
          </div>

        </div>
        <div :class="[{'hidden': swap!=false },'flex flex-col justify-center items-center w-full h-[100%]']">
          <div v-if="lyricsArr.length != 0"
               :class="[{'hidden': swap!= false },'flex flex-col justify-center items-center w-full h-full']">
            <div class="overflow-y-scroll snap-y snap-mandatory
                w-[80%] md:w-full h-full
                text-xl grid-cols-1 grid-rows-1
                bg-gradient-to-l from-black/0 via-primary/10 to-black/0
              "
                 id="lyric_scroll"
                 style="-ms-overflow-style: none;"
            >
              <p class="h-[40%] snap-center"></p>
              <p v-for="(lyric,index) in lyricsArr"
                 :class="[
                   {'font-bold text-2xl': lyric.name != null },//设置
                   {'text-transparent bg-clip-text bg-gradient-to-b from-primary via-secondary to-accent text-3xl md:text-5xl font-extrabold': usePlayerStore().currentLyricIndex === index},//当前歌词
                   {'text-black/30':usePlayerStore().currentLyricIndex !== index},//其他歌词
                   'snap-center text-center h-[20%] px-5 py-5 focus:scroll-mr-80 flex justify-center items-center'
               ]">
                {{ lyric.data }}
              </p>
              <p class="h-[40%] snap-center"></p>
            </div>
          </div>
          <div v-else class="flex flex-col justify-center items-center w-full h-full">暂无歌词</div>
        </div>
      </div>
      <div class="flex flex-col justify-center items-center w-full">
        <div class="flex flex-row justify-center items-center w-full my-6">
          <div @click="afterSound()"
               class="  flex justify-center items-center mx-6">
            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5"
                 stroke="currentColor"
                 class="w-10 h-10 md:w-16 md:h-16">
              <path stroke-linecap="round" stroke-linejoin="round"
                    d="M18.75 19.5l-7.5-7.5 7.5-7.5m-6 15L5.25 12l7.5-7.5"/>
            </svg>
          </div>
          <div @click="playCurrentSong()"
               class="  flex justify-center items-center mx-6">
            <svg v-if="
                 usePlayerStore().playerList[usePlayerStore().currentIndex]?.['id'] ==  song?.['id']
                 ?  !usePlayerStore().isPlaying : true
                "
                 xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5"
                 stroke="currentColor"
                 class="w-10 h-10 md:w-16 md:h-16">
              <path stroke-linecap="round" stroke-linejoin="round"
                    d="M5.25 5.653c0-.856.917-1.398 1.667-.986l11.54 6.348a1.125 1.125 0 010 1.971l-11.54 6.347a1.125 1.125 0 01-1.667-.985V5.653z"/>
            </svg>
            <svg v-else
                 xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5"
                 stroke="currentColor"
                 class="w-10 h-10 md:w-16 md:h-16">
              <path stroke-linecap="round" stroke-linejoin="round" d="M15.75 5.25v13.5m-7.5-13.5v13.5"/>
            </svg>
          </div>
          <div @click="nextSound()"
               class="  flex justify-center items-center mx-6">
            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5"
                 stroke="currentColor"
                 class="w-10 h-10 md:w-16 md:h-16">
              <path stroke-linecap="round" stroke-linejoin="round"
                    d="M11.25 4.5l7.5 7.5-7.5 7.5m-6-15l7.5 7.5-7.5 7.5"/>
            </svg>
          </div>
        </div>
        <div v-if="usePlayerStore().playerList[usePlayerStore().currentIndex]?.id == props.songId"
             class="flex flex-row justify-center items-center w-full">
          <div class="w-2/12">{{ hook_formatTime(usePlayerStore().currentTime) }}</div>
          <input type="range"
                 id="seekBar_SongInfo"
                 v-model="usePlayerStore().currentTime"
                 @mousedown="usePlayerStore().isSeekChange=true"
                 @mouseup="usePlayerStore().isSeekChange=false"
                 min="0"
                 :max="usePlayerStore().duration"
                 step="0.01"
                 @change="seekSound()"
                 class="w-8/12 range">
          <div class="w-2/12">{{ hook_formatTime(usePlayerStore().duration) }}</div>
        </div>
      </div>
      <comments
          class="flex flex-col justify-center items-center w-full mt-12"
          :song-id="songId">
      </comments>
  </div>
</template>

<script setup lang="ts">

import {onBeforeMount, onBeforeUpdate, onMounted, onUpdated, ref, watch} from "vue";
import {hook_findSongById} from "../hook/SongHook.ts";
import {hook_addSongToPlayerList, hook_formatTime, usePlayerStore} from "../hook/SongPlayerHook.ts";
import {Lrc_parse, Lyric_getLyricsById, LyricLine} from "../hook/LyricsHook.ts";
import $ from 'jquery'
import router from "../plugins/router.ts";
import {animate} from "motion";
import {Motion} from "@motionone/vue";
import Comments from "../components/comments.vue";

//TODO data

//用于当前切换页面 (true:唱片页面 ，false:歌词页面)
let swap = ref(true);

let props = defineProps<{
  songId
}>()

let songId = ref(props.songId)
//更新数据
let song = ref()
let lyricsArr = ref([])
let lyrics = ref()

//TODO dom元素
//歌词容器


//TODO 生命周期钩子

onBeforeMount(async () => {
  //获取歌曲信息
  await updateData()
  //获取歌词信息
  await getLyrics()
})
//歌词单位高度：歌词容器一次显示5个歌词 => (歌词单位高度 = 歌词容器高度 / 5)
let unit_height
onMounted(() => {
  //更新数据
  let mainBox = $("#mainBox");
  unit_height = mainBox.height() / 5
  console.log("高度为：" + unit_height)
})

onBeforeUpdate(() => {
  if (song.value?.lyricsId == null) {
    lyricsArr.value = []
  }
})

onUpdated(() => {
  playAnime(usePlayerStore().isPlaying)
})


//TODO function

//当前页面歌曲比较播放歌曲做播放判断
function playCurrentSong() {
  //如果当前播放的歌曲id不等于当前页面歌曲的id
  if(usePlayerStore().playerList[usePlayerStore().currentIndex]?.['id'] !=  song.value?.['id']){
    console.log('不是当前歌曲')
    hook_addSongToPlayerList(song.value, true)
  }else{
    console.log('当前歌曲')
    usePlayerStore().togglePlayPause()
  }
}


//获取歌曲的信息
async function updateData() {
  song.value = await hook_findSongById(props.songId);
}

//获取歌词
async function getLyrics() {
  if (song.value?.lyricsId != null) {
    Lyric_getLyricsById(song.value.lyricsId, async (res) => {
      lyrics.value = res.data
      lyricsArr.value = await Lrc_parse(res.data.url)
      _.pullAllBy(lyricsArr.value, [{data: ""}], {data: ""})
      // console.log(lyricsArr.value)
    })
  }
}

//调整seek
function seekSound() {
  usePlayerStore().seekSound($('#seekBar_SongInfo').prop('value'))
}

//上一首
async function afterSound() {
  await usePlayerStore().afterSound()
  await router.push('/songInfo/' + usePlayerStore().playerList[usePlayerStore().currentIndex]?.id)
}

//下一首
async function nextSound() {
  await usePlayerStore().nextSound()
  await router.push('/songInfo/' + usePlayerStore().playerList[usePlayerStore().currentIndex]?.id)
}

//TODO watch

//id发生变化后重新拉取数据
watch(() => props.songId, async (value) => {
  console.log("id发生变化了")
  //获取歌曲信息
  await updateData()
  //获取歌词信息
  await getLyrics()
  swap.value = true
  songId.value = value
})


//监听歌曲时间获得歌词的index
watch(() => usePlayerStore().currentTime, async (value) => {
  //如果当前播放的歌曲是当前页面的歌曲，才做滚动
  if (usePlayerStore().playerList[usePlayerStore().currentIndex]?.id == song.value.id ?? false) {
    //1.遍历歌词列表
    for (let i = 0; i < lyricsArr.value.length; i++) {
      let lyric = lyricsArr.value[i];
      //2.如果是正常歌词
      if (lyric instanceof LyricLine) {
        //3.比当前时间小的
        if (value * 60 > lyric.time) {
          //4.获取index
          usePlayerStore().currentLyricIndex = i;
        }
      }
    }
  }
})

//监听当前歌词改变时，滑动屏幕到当前歌词位置
watch(() => usePlayerStore().currentLyricIndex, async (value) => {
  // console.log("当前高度:" + unit_height)
  // console.log(lyric_scroll)
  $('#lyric_scroll').scrollTop(unit_height * (usePlayerStore().currentLyricIndex))
})

//监听切换到歌词页面时，更新当前歌词位置
watch(() => swap.value, async (value) => {
  if (value == false) {
    //延时是为了给页面响应时间
    setTimeout(() => {
      $('#lyric_scroll').scrollTop(unit_height * (usePlayerStore().currentLyricIndex))
    }, 100)
  }
})


//TODO watch
watch(() => usePlayerStore().isPlaying, (value) => {
  playAnime(value)
})

function playAnime(value) {
  let animeElement = $('#playAnime')[0];
  if (value == true) {
    //播放
    animate(animeElement, {
      rotate: 40
    })
  } else {
    //暂停
    animate(animeElement, {
      rotate: 80
    })
  }
}


</script>


<style scoped>

.my-button {
  border-radius: 150px;
  background: linear-gradient(145deg, #232323, #1e1e1e);
  box-shadow: 28px 28px 56px #1c1c1c,
  -28px -28px 56px #262626;
}

.my-button:hover {
  border-radius: 150px;
  background: linear-gradient(145deg, #121212, #151515);
  box-shadow: 28px 28px 56px #111111,
  -28px -28px 56px #171717;
}

</style>